import Mock from "mockjs";

let studentList = [
  {
    id: 1,
    studentName: "张三",
    age: 18,
    sex: "男",
    phone: "13078596345",
    address: "湖北省武汉市洪山区",
  },
  {
    id: 2,
    studentName: "李四",
    age: 20,
    sex: "女",
    phone: "13078596346",
    address: "湖北省武汉市江夏区",
  },
  {
    id: 3,
    studentName: "王五",
    age: 21,
    sex: "男",
    phone: "13078598545",
    address: "湖北省武汉市青山区",
  },
];

/* 查询学生列表 */
Mock.mock("/api/getStudentList", "get", () => {
  return {
    message: "ok",
    code: 200,
    data: studentList,
  };
});

/* 删除学生信息 */
Mock.mock("/api/delStudent", "post", (data) => {
  const dId = JSON.parse(data.body).id;
  let datad = studentList.filter((dItem) => dId != dItem.id);
  studentList = datad;
  return {
    message: "ok",
    code: 200,
    data: null,
  };
});

/* 新增学生信息 */
Mock.mock("/api/addStudent", "post", (data) => {
  let addData = JSON.parse(data.body);
  console.log(addData);
  let obj = {
    id: studentList[studentList.length - 1]
      ? studentList[studentList.length - 1].id + 1
      : 1,
    studentName: addData.studentName,
    age: addData.age,
    sex: addData.sex,
    phone: addData.phone,
    address: addData.address,
  };
  studentList.push(obj);
  return {
    message: "ok",
    code: 200,
    data: null,
  };
});

/* 修改学生信息 */
Mock.mock("/api/editStudent", "post", (data) => {
  let editData = JSON.parse(data.body);
  studentList.forEach((item) => {
    if (item.id == editData.id) {
      item.studentName = editData.studentName;
      item.age = editData.age;
      item.sex = editData.sex;
      item.phone = editData.phone;
      item.address = editData.address;
    }
  });
  return {
    message: "ok",
    code: 200,
    data: null,
  };
});
